package com.zsg.webview.Activities;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Parcelable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import com.zsg.webview.Config;
import com.zsg.webview.Listener.MyRecycleViewItemListener;
import com.zsg.webview.R;
import com.zsg.webview.Adapter.RcAdapter;
import com.zsg.webview.ResponseJson.NewWeiboResponse;
import com.zsg.webview.Util.CheckNetWork;
import com.zsg.webview.Util.Net;
import com.zsg.webview.WeiBoBaseClass.Status;

import org.json.JSONObject;

import java.io.Serializable;

public class ShowActivity extends AppCompatActivity implements Config {

    RecyclerView recyclerView;
    RcAdapter adapter;
    RequestQueue requestQueue;
    String access_token;

    //下拉刷新
    SwipeRefreshLayout refreshLayout;

    LinearLayoutManager layoutManager;      //用来操作recycleiew 的布局管理

    float density;  //像素密度

    String allUrl;   //获取当前登录用户及其所关注用户的最新微博 url


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show);

        //读取access_token
        readAccessTaken();
        requestQueue = Net.getInstance(getApplicationContext()).getRequestQueue();


        //得到像素密度
        getDensity();

        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        initView();

        initActionBar();

        //加载数据
        LoadWeiBoData(1, TYPE_REFRESH);
    }

    private void initUrl(int page) {
        //获取当前登录用户及其所关注用户的最新微博 的url   page为加载的页数
        allUrl = "https://api.weibo.com/2/statuses/friends_timeline.json?" +
                "access_token=" + access_token +
                "&count=" + pagecount +
                "&page=" + page;
    }

    private void getDensity() {
        //获得屏幕dpi 像素密度
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);

        density = metric.density;  // 密度（0.75 / 1.0 / 1.5）
        // int densityDpi = metric.densityDpi;  // 密度DPI（120 / 160 / 240）
    }

    private void initActionBar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setDisplayUseLogoEnabled(true);
    }

    /**
     * 初始化recyclerView  adapter  refreshLayout
     */
    private void initView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(adapter);
        adapter = new RcAdapter(this, density);
        recyclerView.setAdapter(adapter);

        //recyclerVie注册 视图项点击监听器  通过adapter来实现
        adapter.registerItemClickListener(new MyRecycleViewItemListener() {
            @Override
            public void onItemClick(View v, int position) {
                //Toast.makeText(ShowActivity.this, "当前点击位置:" + position, Toast.LENGTH_SHORT).show();
                Status status=adapter.getItem(position);
                Intent intent=new Intent(ShowActivity.this,AboutActivity.class);
                intent.putExtra("status", (Serializable) status);
                startActivity(intent);
            }
        });

        layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        //添加滚动监听器
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                // 当不滚动时
                if (newState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到底部
                    //得到可见视图项最底层id
                    int lostPos = layoutManager.findLastVisibleItemPosition();
                    if (lostPos == layoutManager.getItemCount() - 1) {
                        //Toast.makeText(ShowActivity.this, "最后：" + lostPos, Toast.LENGTH_SHORT).show();
                        //检查是否有网络
                        LoadWeiBoData(layoutManager.getItemCount() / pagecount + 1, TYPE_GETMORE);

                    }
                }
            }
        });


        refreshLayout = (SwipeRefreshLayout) findViewById(R.id.refreshlayout);
        //设置颜色
        refreshLayout.setColorSchemeResources(R.color.r, R.color.g, R.color.b);
        //背景色
        // refreshLayout.setProgressBackgroundColorSchemeColor(Color.argb(66,58,123,55));

        //设置刷新的监听器
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //读取微博信息
                LoadWeiBoData(1, TYPE_REFRESH);
            }
        });

    }

    /**
     * 获取保存在磁盘中的AccessTaken
     */
    private void readAccessTaken() {

        SharedPreferences sharedPreferences = getSharedPreferences(FILE_NAME, MODE_PRIVATE);
        // 使用getString方法获得value，注意第2个参数是value的默认值
        access_token = sharedPreferences.getString(TAKEN, "");
        //Log.d(MainActivity.TAG,"access_token: "+access_token);


    }

    /**
     * 网络加载微博数据
     */
    public void LoadWeiBoData(final int page, final int type) {
        // 初始化url信息
        initUrl(page);

        //检查是否有网络
        if (!CheckNetWork.detect(this)) {
            Toast.makeText(this, "亲，木有网哦... 请检查设置", Toast.LENGTH_SHORT).show();
        }


        Log.d(MainActivity.TAG, allUrl);
        JsonObjectRequest request = new JsonObjectRequest(
                Request.Method.GET,
                allUrl,
                null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d(MainActivity.TAG, response.toString());

                        Gson gson = new Gson();
                        NewWeiboResponse s = gson.fromJson(response.toString(), NewWeiboResponse.class);
                        //改变适配器 中的数据
                        adapter.updateData(s.statuses, type);
                        //Log.d(MainActivity.TAG, s.statuses.toString());
                        //停止刷新
                        refreshLayout.setRefreshing(false);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        refreshLayout.setRefreshing(false);
                        //若处于加载更多(翻页)状态 连不上网  缓存页数大于3  则在最后一项显示没网
                        if (page > 3 && type == TYPE_GETMORE) {

                            View v = layoutManager.findViewByPosition(layoutManager.getItemCount() - 1);
                            TextView textView = (TextView) v.findViewById(R.id.textView);
                            textView.setText("还没联网哦，请检查网络设置");
                            v.findViewById(R.id.imageView).setVisibility(View.INVISIBLE);

                        }

                        //没有网就使用缓存数据
                        else if (requestQueue.getCache().get(allUrl) != null) {
                            //通过url的到缓存的数据
                            byte[] data = requestQueue.getCache().get(allUrl).data;
                            Gson gson = new Gson();
                            NewWeiboResponse s = gson.fromJson(new String(data), NewWeiboResponse.class);
                            //改变适配器 中的数据
                            adapter.updateData(s.statuses, type);

                        }
                    }

                }
        );

        Net.getInstance(getApplicationContext())
                .addRequest(request);

    }


}
